package com.mirror.tk.core.biz.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.beust.jcommander.internal.Maps;
import com.google.common.collect.Lists;
import com.mirror.tk.core.biz.common.Result;
import com.mirror.tk.core.biz.dto.GoodsTypeDto;
import com.mirror.tk.core.biz.dto.ResGoodsDetail;
import com.mirror.tk.core.biz.dto.ResGoodsInfo;
import com.mirror.tk.core.biz.dto.ResGoodsSendLog;
import com.mirror.tk.core.biz.dto.ResSendTpl;
import com.mirror.tk.core.biz.dto.ResTaobaoCoupon;
import com.mirror.tk.core.biz.dto.ResTaobaoGoods;
import com.mirror.tk.core.biz.dto.ResTaobaoShop;
import com.mirror.tk.core.biz.dto.ResUserSendContent;
import com.mirror.tk.core.biz.req.ReqAddGoods;
import com.mirror.tk.core.biz.req.ReqGenUserSend;
import com.mirror.tk.core.biz.req.ReqGetSendLog;
import com.mirror.tk.core.biz.req.ReqGoodsInfo;
import com.mirror.tk.core.biz.req.ReqSaveUserTpl;
import com.mirror.tk.core.biz.req.ReqSendLog;
import com.mirror.tk.core.biz.req.ReqTransformUrl;
import com.mirror.tk.core.constant.ErrorCode;
import com.mirror.tk.core.constant.GoodsDictionary;
import com.mirror.tk.core.module.goods.domain.Goods;
import com.mirror.tk.core.module.goods.domain.GoodsCoupon;
import com.mirror.tk.core.module.goods.domain.GoodsImg;
import com.mirror.tk.core.module.goods.domain.GoodsSendLog;
import com.mirror.tk.core.module.goods.domain.GoodsShopInfo;
import com.mirror.tk.core.module.goods.domain.GoodsTplContrast;
import com.mirror.tk.core.module.goods.dto.GoodsInfoDto;
import com.mirror.tk.core.module.goods.dto.TaobaoGoodsDto;
import com.mirror.tk.core.module.goods.service.GoodsCouponService;
import com.mirror.tk.core.module.goods.service.GoodsSendLogService;
import com.mirror.tk.core.module.goods.service.GoodsService;
import com.mirror.tk.core.module.goods.service.GoodsTplContrastService;
import com.mirror.tk.core.module.goods.service.GoodsTypeService;
import com.mirror.tk.core.module.user.domain.UserPid;
import com.mirror.tk.core.module.user.domain.UserSendTpl;
import com.mirror.tk.core.module.user.service.UserPidService;
import com.mirror.tk.core.module.user.service.UserSendTplService;
import com.mirror.tk.core.utils.GoodsUtil;
import com.mirror.tk.core.utils.TaobaoUrlUtil;
import com.mirror.tk.core.utils.TransferUtil;
import com.mirror.tk.framework.common.dao.support.PageInfo;
import com.mirror.tk.framework.utils.Dates;

@Service
public class GoodsBiz {
	
	@Value("${taobao.transform.url}")
	String urlTemplate;
	
	@Value("${taobao.transform.src}")
	String src;

	@Autowired
	GoodsTypeService goodsTypeService;
	
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	GoodsCouponService goodsCouponService;
	
	@Autowired
	TaobaoBiz taobaoBiz;
	
	@Autowired
	GoodsSendLogService goodsSendLogService;
	
	@Autowired
	UserPidService userPidService;
	
	@Autowired
	UserSendTplService userSendTplService;
	
	@Autowired
	GoodsTplContrastService goodsTplContrastService;
	
	// 优惠劵跳转模板
	public static final String PC_URL_TPL = "https://taoquan.taobao.com/coupon/unify_apply.htm?sellerId=%s&activityId=%sscene=taobao_shop";
	public static final String MOBILE_URL_TPL = "http://shop.m.taobao.com/shop/coupon.htm?seller_id=%s&activity_id=%s";
	
	/**
	 * 获取所有商品分类
	 * @return
	 */
	public Result<List<GoodsTypeDto>> getAllGoodsType(){
		List<GoodsTypeDto> result = goodsTypeService.getNormalType();
		int total = 0;
		for(GoodsTypeDto gt : result) {
			total += gt.getGoodsCount() == null ? 0 : gt.getGoodsCount();
		}
		
		GoodsTypeDto totalDto = new GoodsTypeDto();
		totalDto.setName("全部");
		totalDto.setId(-1l);
		totalDto.setGoodsCount(total);
		
		result.add(0, totalDto);
		return new Result<List<GoodsTypeDto>>().success(result);
	}
	
	/**
	 * 分页获取商品列表
	 * @param req
	 * @return
	 */
	public Result<PageInfo<ResGoodsInfo>> getGoodsInfo(ReqGoodsInfo req) {
		Integer cat = req.getCat();
		if(cat == null) {
			return new Result<PageInfo<ResGoodsInfo>>().fail(ErrorCode.GOODS_CAT_ERROR,ErrorCode.GOODS_CAT_ERROR_DES);
		}
		
		if(req.getCurrentPage() == null) {
			req.setCurrentPage(1);
		}
		if(req.getPageSize() == null) {
			req.setPageSize(10);
		}
		
		Map<String,Object> searchMap = Maps.newHashMap();
		PageInfo<GoodsInfoDto> pageInfo = new PageInfo<GoodsInfoDto>(req.getPageSize(),req.getCurrentPage());
		
		if(cat.intValue() == 1) { //今日推荐
			searchMap.put("EQ_recommend", 1);
			searchMap.put("EQ_attribute", 0);
		} else if(cat.intValue() == 2) { //今日新品
			searchMap.put("GT_createTime", TransferUtil.getDay(0));
			searchMap.put("LT_createTime", TransferUtil.getDay(1));
		} else if(cat.intValue() == 3) {//精选直播
			searchMap.put("EQ_recommend", 0);
			searchMap.put("EQ_attribute", 3);
		} else if(cat.intValue() == 4) {//客户端首页
			searchMap.put("EQ_recommend", 0);
			searchMap.put("EQ_attribute", 4);
		} else if(cat.intValue() == 5) {//明日预告
			searchMap.put("EQ_attribute", 5);
			searchMap.put("EQ_adTime", req.getAdTime());
		}
		
		if(req.getName() != null && StringUtils.isNotBlank(req.getName())) {
			searchMap.put("LIKE_name", req.getName());
		}
		
		if(req.getType() != null) {
			searchMap.put("EQ_typeId", req.getType());
		}
		
		if(req.getSource() != null) {
			searchMap.put("EQ_source", req.getSource());
		}
		
		if(req.getPriceHigh() != null) {
			searchMap.put("LT_price", req.getPriceHigh());
		}
		
		if(req.getPriceLow() != null) {
			searchMap.put("GT_price", req.getPriceLow());
		}
		
		if(req.getSalesHigh() != null) {
			searchMap.put("LT_sales", req.getSalesHigh());
		}
		
		if(req.getSalesLow() != null) {
			searchMap.put("GT_sales", req.getSalesLow());
		}
		
		if(req.getComHigh() != null) {
			searchMap.put("LT_commission", req.getComHigh());
		}
		if(req.getComLow() != null) {
			searchMap.put("GT_commission", req.getComLow());
		}
		searchMap.put("EQ_status", Goods.STATUS_PUBLISH);
		
		if(req.getSort() != null) {
			byte sort = req.getSort().byteValue();
			if(sort ==0){ //综合
				searchMap.put("ORDERBY", " g.create_time desc");
			} else if(sort == 1) {//最新
				searchMap.put("ORDERBY", " g.create_time desc");
			} else if(Math.abs(sort) == 2) {//销量
				searchMap.put("ORDERBY", " g.sales " + (sort == 2 ? "desc" : "asc"));
			} else if(Math.abs(sort) == 3) {//佣金
				searchMap.put("ORDERBY", " g.commission " +  (sort == 3 ? "desc" : "asc"));
			} else if(Math.abs(sort) == 4) {//价格
				searchMap.put("ORDERBY", " g.price " + (sort == 4 ? "desc" : "asc"));
			} else if(sort == 5) {//剩余时间
				searchMap.put("ORDERBY", " gc.end_time desc");
			}
		}
		
		pageInfo = goodsService.queryGoodsInfo(pageInfo, searchMap);
		
		if(pageInfo != null) {
			List<GoodsInfoDto> list = pageInfo.getPageResults();
			List<ResGoodsInfo> result = Lists.newArrayList();
			List<Long> ids = Lists.newArrayList();
			for(GoodsInfoDto dto : list) {
				ResGoodsInfo res = new ResGoodsInfo();
				res.setNumIid(dto.getNumIid());
				ids.add(dto.getNumIid());
				res.setImgUrl(dto.getPicUrl());
				res.setCommission(TransferUtil.intToPercent(dto.getCommission()));
				res.setCounponRemained(dto.getRemained());
				res.setCounponTotal(dto.getTotal());
				res.setCouponPrice(dto.getMoney());
				res.setName(dto.getName());
				res.setPrice(dto.getPrice());
				res.setSales(dto.getSales());
				res.setShopName(dto.getTitle());
				res.setCreateTime(DateFormatUtils.format(dto.getCreateTime(), "yyyy-MM-dd"));
				res.setSource(dto.getSource());
				res.setType(dto.getType());
				res.setAdTime(TransferUtil.dateToStr(dto.getAdTime()));
				res.setPlanUrl(dto.getPlanUrl());
				
				result.add(res);
			}			
			PageInfo<ResGoodsInfo> pageResult = new PageInfo<ResGoodsInfo>(pageInfo.getCountOfCurrentPage(), pageInfo.getCurrentPage());
			pageResult.setTotalCount(pageInfo.getTotalCount());
			pageResult.setTotalPage(pageInfo.getTotalPage());
			pageResult.setPageResults(result);
			
			//查找商品小图
			
			List<GoodsImg> imgs = goodsService.queryGoodsImgs(ids);
			Map<Long, List<GoodsImg>> temp = Maps.newHashMap();
			for(GoodsImg img : imgs) {
				List<GoodsImg> ls = temp.get(img.getNumIid());
				if(ls == null) {
					ls = Lists.newArrayList();
					temp.put(img.getNumIid(), ls);
				}
				ls.add(img);
			}
			for(ResGoodsInfo res : result) {
				Long numIid = res.getNumIid();
				List<GoodsImg> ls = temp.get(numIid);
				List<String> is = Lists.newArrayList();
				if(ls != null) {
					for(GoodsImg img: ls) {
						is.add(img.getUrl());
					}
				}
				res.setImgs(is);
			}
			
			return new Result<PageInfo<ResGoodsInfo>>().success(pageResult);
		}
		return new Result<PageInfo<ResGoodsInfo>>().success(new PageInfo<ResGoodsInfo>());
	}
	
	/**
	 * 获取我的商品信息列表
	 * @param currentPage
	 * @param pageSize
	 * @param userId
	 * @param status
	 * @return
	 */
	public Result<PageInfo<ResGoodsInfo>> getMyGoodsInfo(Integer currentPage, Integer pageSize, Long userId, Integer status) {
		
		Map<String,Object> searchMap = Maps.newHashMap();
		PageInfo<GoodsInfoDto> pageInfo = new PageInfo<GoodsInfoDto>(pageSize, currentPage);
		searchMap.put("EQ_userId", userId);
		searchMap.put("EQ_status", status);
		
		pageInfo = goodsService.queryGoodsInfo(pageInfo, searchMap);
		
		if(pageInfo != null) {
			List<GoodsInfoDto> list = pageInfo.getPageResults();
			List<ResGoodsInfo> result = Lists.newArrayList();
			List<Long> ids = Lists.newArrayList();
			for(GoodsInfoDto dto : list) {
				ResGoodsInfo res = new ResGoodsInfo();
				res.setNumIid(dto.getNumIid());
				ids.add(dto.getNumIid());
				res.setImgUrl(dto.getPicUrl());
				res.setCommission(TransferUtil.intToPercent(dto.getCommission()));
				res.setCounponRemained(dto.getRemained());
				res.setCounponTotal(dto.getTotal());
				res.setCouponPrice(dto.getMoney());
				res.setName(dto.getName());
				res.setPrice(dto.getPrice());
				res.setSales(dto.getSales());
				res.setShopName(dto.getTitle());
				res.setCreateTime(DateFormatUtils.format(dto.getCreateTime(), "yyyy-MM-dd"));
				res.setSource(dto.getSource());
				res.setType(dto.getType());
				res.setAdTime(TransferUtil.dateToStr(dto.getAdTime()));
				res.setPlanUrl(dto.getPlanUrl());
				
				result.add(res);
			}			
			PageInfo<ResGoodsInfo> pageResult = new PageInfo<ResGoodsInfo>(pageInfo.getCountOfCurrentPage(), pageInfo.getCurrentPage());
			pageResult.setTotalCount(pageInfo.getTotalCount());
			pageResult.setTotalPage(pageInfo.getTotalPage());
			pageResult.setPageResults(result);
			
			//查找商品小图
			
			List<GoodsImg> imgs = goodsService.queryGoodsImgs(ids);
			Map<Long, List<GoodsImg>> temp = Maps.newHashMap();
			for(GoodsImg img : imgs) {
				List<GoodsImg> ls = temp.get(img.getNumIid());
				if(ls == null) {
					ls = Lists.newArrayList();
					temp.put(img.getNumIid(), ls);
				}
				ls.add(img);
			}
			for(ResGoodsInfo res : result) {
				Long numIid = res.getNumIid();
				List<GoodsImg> ls = temp.get(numIid);
				List<String> is = Lists.newArrayList();
				if(ls != null) {
					for(GoodsImg img: ls) {
						is.add(img.getUrl());
					}
				}
				res.setImgs(is);
			}
			
			return new Result<PageInfo<ResGoodsInfo>>().success(pageResult);
		}
		return new Result<PageInfo<ResGoodsInfo>>().success(new PageInfo<ResGoodsInfo>());
	}
	
	/**
	 * 获取商品详情
	 * @param id
	 * @return
	 */
	public Result<ResGoodsDetail> getDetail(Long id) {
		if(id == null) {
			return new Result<ResGoodsDetail>().fail(ErrorCode.PARAM_NULL,ErrorCode.PARAM_NULL_DES);
		}
		
		GoodsInfoDto dto = goodsService.queryGoodsInfo(id);
		ResGoodsDetail result = new ResGoodsDetail();
		if(dto == null) {
			return new Result<ResGoodsDetail>().success(result);
		}
		result.setNumIid(dto.getNumIid());
		result.setCommission(dto.getCommission());
		result.setConditions(dto.getConditions());
		result.setCouponApplied(dto.getApplied());
		result.setCouponGetUrl(dto.getCouponUrl());
		result.setCouponPrice(dto.getMoney());
		result.setCouponRemained(dto.getRemained());
		result.setDetail(dto.getDetail());
		result.setStartTime(TransferUtil.dateToStr(dto.getStartTime()));
		result.setEndTime(TransferUtil.dateToStr(dto.getEndTime()));
		result.setGoodsUrl(dto.getUrl());
		result.setLimited(dto.getLimited());
		result.setName(dto.getName());
		result.setNumIid(dto.getNumIid());
		result.setPrice(dto.getPrice());
		result.setSales(dto.getSales());
		result.setType(dto.getType());
		result.setShopName(dto.getTitle());
		result.setPicUrl(dto.getPicUrl());
		result.setQq(dto.getQq());
		result.setSubTitle(dto.getSubTitle());
		result.setAdTime(TransferUtil.dateToStr(dto.getAdTime()));
		result.setSource(dto.getSource());
		result.setMobileCounponUrl(dto.getMobileCouponUrl());
		result.setPlanUrl(dto.getPlanUrl());
		result.setTypeId(dto.getTypeId());
		
		//查询小图
		List<Long> ids = Lists.newArrayList();
		ids.add(dto.getNumIid());
		List<GoodsImg> imgs = goodsService.queryGoodsImgs(ids);
		if(!CollectionUtils.isEmpty(imgs)) {
			List<String> smallImg = Lists.newArrayList();
			for(GoodsImg img : imgs) {
				smallImg.add(img.getUrl());
			}
			result.setSmallImg(smallImg);
		}
		return new Result<ResGoodsDetail>().success(result);
	}
	
	/**
	 * 添加商品 
	 * @param req
	 * @return
	 * @throws Exception 
	 */
	public Result<Long> addGoods(ReqAddGoods req) throws Exception {
		if(validateAddGoods(req)) {
			return Result.error(ErrorCode.PARAM_NULL, ErrorCode.PARAM_NULL_DES);
		}
		TaobaoGoodsDto dto = GoodsUtil.resolveGoods(req.getGoodsUrl());
		if(null == dto){
			return Result.error(ErrorCode.GOODS_IN_TAOBAO_NOT_EXIST_ERROR, ErrorCode.GOODS_IN_TAOBAO_NOT_EXIST_ERROR_DES);
		}
		Long numIid = dto.getNumIid();
		Result<ResTaobaoGoods> r = taobaoBiz.fetchGoods(numIid);
		if(!r.isSuccess() || r.getData() == null || r.getData().getNumIid() == null) {
			return Result.error(ErrorCode.GOODS_IN_TAOBAO_NOT_EXIST_ERROR,ErrorCode.GOODS_IN_TAOBAO_NOT_EXIST_ERROR_DES+":"+numIid);
		}
		Goods g = goodsService.queryGoods(numIid);
		if(g != null) {
			return Result.error(ErrorCode.GOODS_EXIST_ERROR, ErrorCode.GOODS_EXIST_ERROR_DES); 
		}
		
		Result<ResTaobaoShop> shopResult = taobaoBiz.fetchShop(numIid);
		if(!shopResult.isSuccess()) {
			return Result.error(shopResult.getCode(), shopResult.getDescription());
		}
		ResTaobaoShop shop = shopResult.getData();
		if(shop.getSellerId() == null) {
			return Result.error(ErrorCode.TAOBAO_SHOP_ERROR,ErrorCode.TAOBAO_SHOP_ERROR_DES);
		}
		
		GoodsShopInfo goodsShopInfo = new GoodsShopInfo();
		goodsShopInfo.setTitle(shop.getShopTitle());
		goodsShopInfo.setSid(shop.getSellerId());
		goodsShopInfo.setPictUrl(shop.getPictUrl());
		goodsShopInfo.setShopUrl(shop.getShopUrl());
		goodsShopInfo.setSellerId(shop.getSellerId());
		goodsShopInfo.setSellerNick(shop.getSellerNick());
		goodsShopInfo.setStatus(1);
		goodsShopInfo.setCreateTime(new Date());
		
		Goods goods = new Goods();
		goods.setAttribute(0);
		goods.setType(req.getPlan());
		goods.setCreateTime(new Date());
		goods.setUserId(req.getUserId());
		goods.setIsCoupon(StringUtils.isNotBlank(req.getCouponUrl()) ? 1 : 0);
		goods.setName(dto.getName());
		goods.setNumIid(dto.getNumIid());
		goods.setPicUrl(dto.getPicUrl());
		goods.setFinalPrice(dto.getFinalPrice());
		goods.setPrice(dto.getPrice());
		goods.setSales(dto.getSales());
		goods.setTypeId(req.getTypeId());
		goods.setUrl(dto.getUrl());
		goods.setPlanUrl(req.getPlanUrl());
		goods.setSource(dto.getSource() == 1 ? 1 : 2);
		goods.setIsExtend(0);
		goods.setCreateTime(new Date());
		goods.setDetail(req.getMemo());
		goods.setCommission(req.getCommission());
		goods.setRecommend(0);
		goods.setAttribute(req.getAttr());
		goods.setStatus(Goods.STATUS_CHECKING);
		goods.setQq(req.getQq());
		goods.setSubTitle(req.getSubTitle());
		if(req.getAttr() != null && req.getAttr().byteValue() == 5) {
			goods.setAdTime(TransferUtil.strToDate(req.getAdTime()));
		}
		
		List<GoodsImg> goodsImg = Lists.newArrayList();
		if(!CollectionUtils.isEmpty(r.getData().getSmallImg())) {
			for(String smallimg : r.getData().getSmallImg()) {
				GoodsImg img = new GoodsImg();
				img.setUrl(smallimg);
				goodsImg.add(img);
			}
		}
		
		// 优惠劵信息
		String activityId = TaobaoUrlUtil.fetchActivityId(req.getCouponUrl());
		if(null == goods.getNumIid() || StringUtils.isBlank(activityId)){
			return Result.error(ErrorCode.COUPON_URL_ERROR, ErrorCode.COUPON_URL_ERROR_DES); 
		}
		Result<ResTaobaoCoupon> couponRes = taobaoBiz.fetchCoupon(goods.getNumIid(), activityId);
		if(null == couponRes) {
			return Result.error(ErrorCode.COUPON_URL_ERROR, ErrorCode.COUPON_URL_ERROR_DES);
		}
		
		goodsService.addGoods(goods, transforCoupon(couponRes.getData(), goodsShopInfo.getSellerId()), goodsImg, goodsShopInfo);
		return new Result<Long>().success(numIid);
	}
	
	/**
	 * 修改商品
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public Result<Long> updasteGoods(ReqAddGoods req)  throws Exception {
		if(validateAddGoods(req)) {
			return Result.error(ErrorCode.PARAM_NULL, ErrorCode.PARAM_NULL_DES);
		}
		
		// 获取商品信息
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("EQ_numIid", req.getId());
		map.put("EQ_userId", req.getUserId());
		List<Goods> list = goodsService.query(map, new HashMap<String, Boolean>());
		if(null == list || list.isEmpty()){
			return Result.error(ErrorCode.GOODS_NOT_EXIST_ERROR, ErrorCode.GOODS_NOT_EXIST_ERROR_DES); 
		}
		Goods g = list.get(0);
		g.setType(req.getPlan());
		g.setIsCoupon(StringUtils.isNotBlank(req.getCouponUrl()) ? 1 : 0);
		g.setCommission(req.getCommission());
		g.setTypeId(req.getTypeId());
		g.setPlanUrl(req.getPlanUrl());
		g.setIsExtend(0);
		g.setDetail(req.getMemo());
		g.setRecommend(0);
		g.setAttribute(req.getAttr());
		g.setStatus(Goods.STATUS_CHECKING);
		g.setQq(req.getQq());
		g.setSubTitle(req.getSubTitle());
		g.setUpdateTime(new Date());
		if(req.getAttr() != null && req.getAttr().byteValue() == 5) {
			g.setAdTime(TransferUtil.strToDate(req.getAdTime()));
		}
		goodsService.update(g);
		
		// 判断是否需要重新获取优惠劵信息
		map.clear();
		map.put("EQ_goodsId", g.getId());
		List<GoodsCoupon> couponList = goodsCouponService.query(map, new HashMap<String, Boolean>());
		if(null == couponList || couponList.isEmpty()){
			return Result.error(ErrorCode.GOODS_EXIST_ERROR, ErrorCode.GOODS_EXIST_ERROR_DES); 
		}
		
		GoodsCoupon coupon = couponList.get(0);
		//不相同就重新拉取优惠劵信息
		if(!(req.getCouponUrl().equalsIgnoreCase(coupon.getPcUrl()) || req.getCouponUrl().equalsIgnoreCase(coupon.getMobileUrl()))){
			// 删除前将sellerId保留
			Long sellerId = coupon.getSellerId();
			// 删除优惠劵
			goodsCouponService.remove(coupon);
			// 重新拉取保存优惠劵
			String activityId = TaobaoUrlUtil.fetchActivityId(req.getCouponUrl());
			if(null == g.getNumIid() || StringUtils.isBlank(activityId)){
				return Result.error(ErrorCode.COUPON_URL_ERROR, ErrorCode.COUPON_URL_ERROR_DES);
			}
			Result<ResTaobaoCoupon> couponRes = taobaoBiz.fetchCoupon(g.getNumIid(), activityId);
			if(null == couponRes) {
				return Result.error(ErrorCode.COUPON_URL_ERROR, ErrorCode.COUPON_URL_ERROR_DES);
			}
			// 转换优惠劵对象
			GoodsCoupon goodsCoupon = transforCoupon(couponRes.getData(), sellerId);
			goodsCoupon.setGoodsId(g.getId());
			goodsCouponService.save(goodsCoupon);
		}
		
		return new Result<Long>().success(g.getNumIid());
	}
	
	
	/**
	 * 添加商品发送记录
	 * @param req
	 * @return
	 */
	public Result<Void> addSendLog(ReqSendLog req) {
		if(req.getNumIid() == null || req.getUserId() == null) {
			return new Result<Void>().fail(ErrorCode.PARAM_NULL, ErrorCode.PARAM_NULL_DES);
		}
		Long numIid = req.getNumIid();
		
		GoodsSendLog goodsSendLog = new GoodsSendLog();
		goodsSendLog.setNumIid(numIid);
		goodsSendLog.setUserId(req.getUserId());
		goodsSendLog.setType(req.getType());
		goodsSendLog.setSendTime(TransferUtil.strToDate(req.getSendTime(),"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"));
		goodsSendLog.setSendGroup(req.getGroup());
		goodsSendLog.setCount(req.getCount());
		goodsSendLog.setCommission(req.getCommission());
		
		Goods goods = goodsService.queryGoods(numIid);
		if(goods != null) {
			goodsSendLog.setCommission(goods.getCommission());
			goodsSendLog.setSource(goods.getSource());
			goodsSendLog.setTitle(goods.getName());
			goodsSendLog.setQq(goods.getQq());
		} else {
			Result<ResTaobaoGoods> result = taobaoBiz.fetchGoods(numIid);
			if(result.isSuccess() && result.getData().getNumIid() != null) {
				ResTaobaoGoods res = result.getData();
				goodsSendLog.setSource( (res.getUserType().intValue() == 1 ? 1 : 2) );
				goodsSendLog.setQq(req.getQq());
				goodsSendLog.setTitle(res.getTitle());
			} else {
				return new Result<Void>().fail(ErrorCode.GOODS_NOT_EXIST_ERROR, ErrorCode.GOODS_NOT_EXIST_ERROR_DES+":"+numIid);
			}
		}
		goodsSendLogService.save(goodsSendLog);
		return new Result<Void>().success();
	}
	
	/**
	 * 得到发送记录
	 * @param userId
	 * @return
	 */
	public Result<PageInfo<ResGoodsSendLog>> getPagedSendLog(ReqGetSendLog req) {
		if(req.getPageSize() == null ) {
			req.setPageSize(10);
		}
		if(req.getCurrentPage() == null) {
			req.setCurrentPage(1);
		}
		if(req.getUserId() == null) {
			return new Result<PageInfo<ResGoodsSendLog>>().fail(ErrorCode.PARAM_NULL,ErrorCode.PARAM_NULL_DES);
		}
		
		PageInfo<GoodsSendLog> page = new PageInfo<GoodsSendLog>(req.getPageSize(),req.getCurrentPage());
		page = goodsSendLogService.getPagedSendLog(page, req.getUserId(), TransferUtil.strToDate(req.getStartTime()),
				TransferUtil.strToDate(req.getEndTime()), req.getTitle());
		
		PageInfo<ResGoodsSendLog> result = new PageInfo<ResGoodsSendLog>(req.getPageSize(),req.getCurrentPage()); 
		result.setCountOfCurrentPage(page.getCountOfCurrentPage());
		result.setTotalCount(page.getTotalCount());
		result.setTotalPage(page.getTotalPage());
		result.setPageResults(new ArrayList<ResGoodsSendLog>());
		for(GoodsSendLog log : page.getPageResults()) {
			ResGoodsSendLog res = new ResGoodsSendLog();
			res.setCommission(TransferUtil.intToPercent(log.getCommission()));
			res.setCount(log.getCount());
			res.setId(log.getId());
			res.setNumIid(log.getNumIid());
			res.setQq(log.getQq());
			res.setSendGroup(log.getSendGroup());
			res.setSendTime(log.getSendTime());
			res.setSource(log.getSource());
			res.setTitle(log.getTitle());
			res.setType(log.getType());
			res.setUserId(log.getUserId());
			result.getPageResults().add(res);
		}
		
		return new Result<PageInfo<ResGoodsSendLog>>().success(result);
	}
	
	/**
	 * 链接转换
	 * @param req
	 * @return
	 */
	public Result<String> transformUrl(ReqTransformUrl req){
		if(req.getUserId() == null || req.getUrl() == null || req.getCouponUrl() == null) {
			return Result.nullError();
		}
		
		String activityId = TaobaoUrlUtil.fetchActivityId(req.getCouponUrl());
		
		String id = TaobaoUrlUtil.fetchItemId(req.getUrl());
		if(StringUtils.isEmpty(id)) {
			return new Result<String>().fail(ErrorCode.URL_ERROR,ErrorCode.URL_ERROR_DES);
		}
		
		Goods goods = goodsService.queryGoods(Long.valueOf(id));
		if(goods == null) {
			return Result.error(ErrorCode.GOODS_NOT_EXIST_ERROR, ErrorCode.GOODS_NOT_EXIST_ERROR_DES);
		}
		
		UserPid userPid = userPidService.getByUserIdAndId(req.getGorup(), req.getUserId());
		if(userPid == null) {
			return Result.error(ErrorCode.USER_PID_NOT_FOUND,ErrorCode.USER_PID_NOT_FOUND_DES);
		}
		
		Integer type = goods.getType();
		if(type == null) {
			return Result.error(ErrorCode.GOODS_TYPE_ERROR, ErrorCode.GOODS_TYPE_ERROR_DES);
		}
		
		String pid = userPid.getQueqiaoPid();
		if(type.byteValue() != Goods.TYPE_QUEQIAO) {
			pid = userPid.getCommonPid();
		}
		
		String url = TaobaoUrlUtil.transformItemUrl(urlTemplate, src, activityId, pid, id, type == Goods.TYPE_DINGXIANG);
		return new Result<String>().success(url);
	}
	
	/**
	 * 获取模板可选参数
	 * @return
	 */
	public Result<List<ResSendTpl>> getListTpl() {
		List<GoodsTplContrast> list = goodsTplContrastService.getAll();
		List<ResSendTpl> result = Lists.newArrayList();
		for(GoodsTplContrast g : list) {
			ResSendTpl r = new ResSendTpl();
			r.setId(g.getId());
			r.setName(g.getName());
			result.add(r);
		}
		return new Result<List<ResSendTpl>>().success(result);
	}
	
	/**
	 * 保存用户发送模板
	 * @param req
	 * @return
	 */
	public Result<Void> saveUserTpl(ReqSaveUserTpl req){
		if(req.getContent() == null || req.getUserId() == null || req.getGroup() == null) {
			return Result.nullError();
		}
		
		UserPid userPid = userPidService.getByUserIdAndId(req.getGroup(), req.getUserId());
		if(userPid == null) {
			return Result.error(ErrorCode.USER_PID_NOT_FOUND, ErrorCode.USER_PID_NOT_FOUND_DES);
		}
		
		UserSendTpl ust = userSendTplService.queryByUserId(req.getUserId());
		if(ust != null) {
			ust.setContent(req.getContent());
			ust.setPid(req.getGroup());
			userSendTplService.update(ust);
		}else {
			ust = new UserSendTpl();
			ust.setContent(req.getContent());
			ust.setPid(req.getGroup());
			ust.setUserId(req.getUserId());
			userSendTplService.save(ust);
		}
		
		return new Result<Void>().success();
	}
	
	/**
	 * 根据模板生成文案
	 * @param userId
	 * @return
	 */
	public Result<ResUserSendContent> generateUserSend(ReqGenUserSend req) {
		if(req.getUserId() == null || req.getNumIid() == null ) {
			return Result.nullError();
		}
		
		UserSendTpl ust = userSendTplService.queryByUserId(req.getUserId());
		if(ust == null) {
			return new Result<ResUserSendContent>().fail(ErrorCode.USER_SEND_TPL_NOT_SET, ErrorCode.USER_SEND_TPL_NOT_SET_DES);
		}
		
		GoodsInfoDto goods = goodsService.queryGoodsInfo(req.getNumIid());
		if(goods == null) {
			return new Result<ResUserSendContent>().fail(ErrorCode.GOODS_NOT_EXIST_ERROR, ErrorCode.GOODS_NOT_EXIST_ERROR_DES);
		}
		
		UserPid userPid = userPidService.get(ust.getPid());
		if(userPid == null) {
			return Result.error(ErrorCode.USER_PID_NOT_FOUND, ErrorCode.USER_PID_NOT_FOUND_DES);
		}
		String pid = userPid.getQueqiaoPid();
		if(goods.getType().byteValue() != Goods.TYPE_QUEQIAO) {
			pid = userPid.getCommonPid();
		}
		
		Map<String, String> map = generateTplMap(goods, pid);
		
		String content = ust.getContent();
		for(String key : map.keySet()) {
			if(map.get(key) != null) {
				content = content.replaceAll(key, map.get(key));
			}
		}
		
		ResUserSendContent result = new ResUserSendContent();
		result.setContent(content);
		return new Result<ResUserSendContent>().success(result);
	}
	
	@Transactional
	public Result<Void> updateGoodsTask() throws Exception{
		List<GoodsCoupon> list = goodsCouponService.findByNormal();
		if (null != list && !list.isEmpty()) {
			for (GoodsCoupon coupon : list) {
				Goods goods = goodsService.get(coupon.getGoodsId());
				Result<ResTaobaoCoupon> couponRes = taobaoBiz.fetchCoupon(goods.getNumIid(), coupon.getActivityId());
				if(null == couponRes) {
					return Result.error(ErrorCode.COUPON_URL_ERROR, ErrorCode.COUPON_URL_ERROR_DES);
				}
				// 转换优惠劵对象
				GoodsCoupon goodsCoupon = transforCoupon(couponRes.getData(), coupon.getSellerId());
				goodsCoupon.setGoodsId(goods.getId());
				goodsCouponService.update(goodsCoupon);
				// 更新商品
				if (coupon.getRemained() == 0 || coupon.getEndTime().getTime() <= new Date().getTime()) {
					// 如果优惠劵已领取完毕或者优惠劵已过期，将商品下架
					goods.setStatus(goods.getIsExtend() == Goods.Extend_true ? Goods.STATUS_PENDING_SETTLEMENT : Goods.STATUS_SHELVES);
					goods.setUpdateTime(new Date());
					goodsService.update(goods);
				} else {
					// 直接更新商品数量
					TaobaoGoodsDto dto = GoodsUtil.resolveGoods(goods.getUrl());
					goodsService.updateById(goods.getId(), dto.getSales());
				}
			}
		}
		return Result.create();
	}
	
	public static final String PIC_TPL = "<img src=\"%s\" />";
	public static final String URL_TPL = "<a href=\"%s\" target=\"_blank\">%s</a>";
	private Map<String, String> generateTplMap(GoodsInfoDto goods,String pid) {
		Map<String, String> map = Maps.newHashMap();
		map.put("\\{商品图片\\}", String.format(PIC_TPL, goods.getPicUrl()));
		map.put("\\{原标题\\}",goods.getName());
		map.put("\\{介绍文案\\}", goods.getDetail());
		map.put("\\{店铺类型\\}", GoodsDictionary.get("source", String.valueOf(goods.getSource())));
		map.put("\\{原价\\}",String.valueOf(goods.getPrice()));
		map.put("\\{券后价\\}", new BigDecimal(goods.getPrice()).subtract(new BigDecimal(goods.getMoney())).toString());
		map.put("\\{销量\\}",String.valueOf(goods.getSales()));
		map.put("\\{佣金比例\\}", TransferUtil.intToPercent(goods.getCommission()));
		map.put("\\{领券链接\\}", String.format(URL_TPL, goods.getCouponUrl(), goods.getCouponUrl()));
		map.put("\\{短标题\\}",goods.getSubTitle());
		map.put("\\{换行符\\}", "<br>");
		map.put("\\{空格符\\}", "&nbsp;&nbsp;");
		map.put("\\{券满\\}", String.valueOf(goods.getConditions() / (double)100));
		map.put("\\{券减\\}", String.valueOf(goods.getMoney()));
		map.put("\\{优惠券剩余数量\\}", String.valueOf(goods.getRemained()));
		map.put("\\{传统模式下单链接\\}", String.format(URL_TPL, goods.getUrl(), goods.getUrl()));
		map.put("\\{二合一模式下单链接\\}", String.format(URL_TPL, TaobaoUrlUtil.transformItemUrl(urlTemplate, src, goods.getActivityId(), pid, goods.getNumIid().toString(), goods.getType() == Goods.TYPE_DINGXIANG), TaobaoUrlUtil.transformItemUrl(urlTemplate, src, goods.getActivityId(), pid, goods.getNumIid().toString(), goods.getType() == Goods.TYPE_DINGXIANG)));
		return map;
	}
	
	/**
	 * 转换优惠劵对象
	 * @param req
	 * @return
	 * @throws Exception
	 */
	private GoodsCoupon transforCoupon(ResTaobaoCoupon res, Long sellerId){
		if(null == res){
			return null;
		}
		// 转换对象
		GoodsCoupon goodsCoupon = new GoodsCoupon();
		goodsCoupon.setActivityId(res.getCouponActivityId());
		goodsCoupon.setMoney(res.getCouponAmount());
		goodsCoupon.setStartTime(Dates.parse(res.getCouponStartTime()));
		goodsCoupon.setEndTime(Dates.parse(res.getCouponEndTime()));
		goodsCoupon.setConditions(res.getCouponStartFee());
		goodsCoupon.setRemained(res.getCouponRemainCount().intValue());
		goodsCoupon.setTotal(res.getCouponTotalCount().intValue());
		// 设置连接
		goodsCoupon.setMobileUrl(String.format(MOBILE_URL_TPL, sellerId, goodsCoupon.getActivityId()));
		goodsCoupon.setPcUrl(String.format(PC_URL_TPL, sellerId, goodsCoupon.getActivityId()));
		goodsCoupon.setCreateTime(new Date());
		return goodsCoupon;
	}
	
	private boolean validateAddGoods(ReqAddGoods req) {
		if(req.getGoodsUrl() == null || req.getCouponUrl() == null ){
			return true;
		}
		return false;
	}
	
}
